﻿// serialport.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <locale>
#include <codecvt>
using namespace std;

#include "../arduino/arduino_parser.h"

#define MAX_BUFFER_SIZE 1024

int _tmain(int argc, _TCHAR* argv[])
{
	int ret = 0;
#ifdef _DEBUG
	bool bTest = true;
#else
	bool bTest = false;
#endif//
	if (argc>2)
	{
		if (_tcsicmp(argv[1], _T("arduino")) == 0)
		{
			if (_tcsicmp(argv[2], _T("-parse")) == 0)
			{
				if (argc > 4) try
				{
					bTest = false;
					//char srcFile[260] = { 0 };
					//char boardFile[260] = { 0 };
					//TextCodeHelper::ToUtf8String(argv[3], srcFile, 260);
					//TextCodeHelper::ToUtf8String(argv[4], boardFile, 260);
					//const char* GBK_LOCALE_NAME = ".936"; //GBK在windows下的locale name
					//									  //构造GBK与wstring间的转码器（wstring_convert在析构时会负责销毁codecvt_byname，所以不用自己delete）
					//wstring_convert<codecvt_byname<wchar_t, char, mbstate_t>> cv1(new codecvt_byname<wchar_t, char, mbstate_t>(GBK_LOCALE_NAME));
					//wstring wtype = cv1.from_bytes(type);
					wstring_convert<codecvt_utf8<wchar_t>> cv2;
					string srcFile = cv2.to_bytes(argv[3]);
					string boardFile = cv2.to_bytes(argv[4]);
					string jsonOut;
					arduino_parse(srcFile
						, boardFile
						, jsonOut);
					std::cout << jsonOut << std::endl;
				}
				catch (logic_error& e)
				{
					auto what = e.what();
					cout << what << endl;
					ret = -1;
				}
				catch (...)
				{
					cout << "unknown error" << endl;
					ret = -2;
				}
			}
		}
	}
	if (bTest)
	{
		try 
		{
			string srcFile = "../../test/闪烁.ino";
			string boardFile = "../../test/desc.json";
			string jsonOut;
			std::cout << srcFile << '\n' << boardFile << '\n';
			arduino_parse(srcFile
				, boardFile
				, jsonOut);
			std::cout << jsonOut << std::endl;
		}
		catch (logic_error& e)
		{
			auto what = e.what();
			cout << what << endl;
		}
		catch (...)
		{
			cout << "unknown error" << endl;
		}
	}
#ifdef _DEBUG
	system("pause");
#endif
	return ret;
}

